<?php

namespace app\admin\controller;

use app\admin\model\Permission as PermissionModel;
use app\BaseController;
use think\facade\View;

class Permission extends BaseController
{
    public function index()
    {
        $type = PermissionModel::group('type')->column('type');
        View::assign('type', $type);
        return view();
    }

    public function list_data()
    {
        $permissions = new PermissionModel;
        $limit = input('limit');
        $type = input('type');
        if($type){
            $permissions = $permissions->where('type',$type);
        }
        $permissions = $permissions->order('id', 'desc')->paginate($limit);
        return lay_data($permissions);
    }

    public function save()
    {
        try {
            $data  = $this->request->only(['name', 'display_name','type']);
            $check = PermissionModel::where('name', $data['name'])->count();
            if ($check) {
                return msg_error('名称/规则重复');
            }
            $permission = (new PermissionModel)->createAndLog($data);

            return return_true_or_false($permission);
        } catch (\Exception $e) {
            return msg_error($e->getMessage());
        }
    }


    public function update($id)
    {
        try {
            $field      = $this->request->only(['display_name','type']);
            $permission = PermissionModel::find($id);
            if (!$permission) {
                return msg_error('权限不存在');
            }

            $permission->display_name = $field['display_name'];
            $permission->type = $field['type'];
            $info                     = $permission->saveAndLog();

            return return_true_or_false($info);

        } catch (\Exception $e) {
            return msg_error($e->getMessage());
        }
    }

    public function delete($id)
    {
        try {
            $permission = PermissionModel::find($id);
            $info       = $permission->deleteAndLog();

            return return_true_or_false($info);
        } catch (\Exception $e) {
            return msg_error($e->getMessage());
        }
    }

}